今天介紹如何使用python與webhook的方式與Dialogflow溝通&給予回應內容
Dialogflow 網站 : https://dialogflow.com/
這邊以問天氣為範例
1.先創建一個entity,以location做為分類
value分別加入各地區(ex:Tainan,Tapei...)
2.建立一個Intent
取個名-->這邊叫askweather
接著再Action的地方
也取個名字,並引入步驟一的entity
3.輸入User Says並標記
確認一下Value是不是對的
做好後記得先按 SAVE 儲存!!!
4.從Dialogflow可以看到傳遞訊息的json
按一下Show Json
可以看到有一部分如下
5.接著進入程式的部分
這個程式是做解析json檔,透過webhook傳遞訊息的部分
#!/usr/bin/env python
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route("/", methods=['GET'])
def hello():
    return "Hello World!"
@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    print("Request:")
    print(json.dumps(req, indent=4))
    res = makeWebhookResult(req)
    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r
def makeWebhookResult(req):
    #askweather的地方是Dialogflow>Intent>Action 取名的內容
    if req.get("result").get("action") != "askweather":
        return {}
    result = req.get("result")
    parameters = result.get("parameters")
    #parameters.get("weatherlocation")的weatherlocation是Dialogflow > Entitiy
    #也就是步驟josn格式中parameters>weatherlocation
    zone = parameters.get("weatherlocation")
    #先設定一個回應
    #如果是Taipei,cost的位置就回營18
    cost = {'Taipei':'18', 'Kaohsiung':'20', 'Taichung':'10','Tainan':'25'}
    #speech就是回應的內容
    speech = "The temperatrue of " + zone + " is " + str(cost[zone])
    print("Response:")
    print(speech)
    #回傳
    return {
        "speech": speech,
        "displayText": speech,
        #"data": {},
        #"contextOut": [],
        "source": "agent"
    }
if __name__ == "__main__":
    app.run(debug=True,port=80)
寫好後
5.一樣在Windows PowerShell(系統管理員)開啟執行
$cd 找到檔案位置
$python 檔名.py
6.打開ngrok得到https的網址
(可以參考Day2)
7.把https網址貼至Dialogflow>Fullfillment>Webhook
記得打開成Enable
還有網址後要多 /webhook (因為程式碼 @app.route('/webhook'...) ->路徑要對好)
8.回到DialogFlow > Intent 點選下方的 Fulfillment
Use Webhook的地方打勾勾
記得SAVE!!!
9.測試一下
我在python app.py 那部分出現了這個問題,可是我有pip flask 惹~~~
為什麼會這樣???
Traceback (most recent call last):
File "app.py", line 7, in 
from flask import Flask
ModuleNotFoundError: No module named 'flask'